<?php

namespace App\Common\Comp;

use App\Common\RedisCache\AreaCache;
use App\Common\RedisCache\SensitiveWordsCache;
use App\Model\SensitiveWords;
use DfaFilter\SensitiveHelper;

class SensitiveWordsComp
{
    protected static $handle = null;

    private function __construct()
    {
    }

    private function __clone()
    {
    }

    /**
     * 获取实例
     */
    public static function getInstance($word_path = [])
    {
        if (!self::$handle) {
            self::$handle = SensitiveHelper::init();

            $redis_cache = new SensitiveWordsCache();
            $redis_cache->setKeyParameter();
            $res = $redis_cache->get();
            if (!$res){
               self::getSensitiveWords();
            }

            if (!empty($res)){
                self::$handle->setTree($res);
            }

        }

        return self::$handle;
    }

    /**
     * 获取敏感词汇并存入Redis
     * @return array
     */
    public static function getSensitiveWords()
    {
        $model = new SensitiveWords();
        $data = $model::query()->select('content')->where(['is_del'=>1])->orderBy('id','DESC')->get()->toArray();
        $res = array_column($data,'content');

        $redis_cache = new SensitiveWordsCache();
        $redis_cache->setKeyParameter();
        $redis_cache->set($res);
        return $res;
    }



    /**
     * 检测是否含有敏感词
     */
    public static function isLegal($content)
    {
        return self::getInstance()->islegal($content);
    }

    /**
     * 敏感词过滤
     */
    public static function replace($content, $replace_char = '*', $repeat = false, $match_type = 1)
    {
        return self::getInstance()->replace($content, $replace_char, $repeat, $match_type);
    }

    /**
     * 标记敏感词
     */
    public static function mark($content, $start_tag, $end_tag, $match_type = 1)
    {
        return self::getInstance()->mark($content, $start_tag, $end_tag, $match_type);
    }

    /**
     * 获取文本中的敏感词
     */
    public static function getBadWord($content, $match_type = 1, $word_num = 0)
    {
        return self::getInstance()->getBadWord($content, $match_type, $word_num);
    }

    /**
     * 返回敏感词信息
     * @param $content
     * @return string
     */
    public static function checkReturnContent($content){
        $str = false;
        if(self::isLegal($content)){
            $contentArr =  self::getBadWord($content);
            if($contentArr){
                $str = implode(",", $contentArr);
                $str = "该内容含有敏感词:".$str;
            }
        }
        return $str;
    }
}
